<template>
  <div class="app-container home">
    <el-container  v-loading="loading" >
      <el-main width="0">
        <el-row :gutter="5">
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
            <el-card shadow="hover">
              <div class="card">
                <div class="font-bold">
                  <span>今日累计发放任务</span>
                  <span class="text">{{homeData.taskToDay+"个"}}</span>
                  <div class="number">昨日累计发放任务：<span class="money"> {{homeData.taskYesterday+"个"}} </span></div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
            <el-card shadow="hover">
              <div class="card">
                <div class="font-bold">
                  <span>今日累计发放金额</span>
                  <span class="text">{{formattedTotal(homeData.payslipToDay)}}</span>
                  <div class="number">昨日累计发放金额：<span class="money"> {{formattedTotal(homeData.payslipYesterday)}} </span></div>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
            <el-card shadow="hover">
              <div class="card">
                <div class="font-bold">
                  <span>今日累计分润金额</span>
                  <span class="text">{{formattedTotal(homeData.separateToDay)}}</span>
                  <div class="number">昨日累计分润金额：<span class="money"> {{formattedTotal(homeData.separateYesterday)}} </span></div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
            <el-card shadow="hover">
              <div class="card">
                <div class="font-bold">
                  <span>今日累计提现金额</span>
                  <span class="text">{{formattedTotal(homeData.withdrawalToDay)}}</span>
                  <div class="number">昨日累计提现金额：<span class="money"> {{formattedTotal(homeData.withdrawalYesterday)}} </span></div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
            <el-card shadow="hover">
              <div class="card">
                <div class="font-bold">
                  <span>月累计发放任务</span>
                  <span class="text">{{homeData.taskCurrentMonth+"个"}}</span>
                  <div class="number">上月累计发放任务：<span class="money"> {{homeData.taskLastMonth+"个"}} </span></div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
            <el-card shadow="hover">
              <div class="card">
                <div class="font-bold">
                  <span>本月累计发放金额</span>
                  <span class="text">{{formattedTotal(homeData.payslipCurrentMonth)}}</span>
                  <div class="number">上月累计发放金额：<span class="money"> {{formattedTotal(homeData.payslipLastMonth)}} </span></div>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
            <el-card shadow="hover">
              <div class="card">
                <div class="font-bold">
                  <span>本月累计分润金额</span>
                  <span class="text">{{formattedTotal(homeData.separateCurrentMonth)}}</span>
                  <div class="number">上月累计分润金额：<span class="money"> {{formattedTotal(homeData.separateLastMonth)}} </span></div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
            <el-card shadow="hover">
              <div class="card">
                <div class="font-bold">
                  <span>本月累计提现金额</span>
                  <span class="text">{{formattedTotal(homeData.withdrawalCurrentMonth)}}</span>
                  <div class="number">上月累计提现金额：<span class="money"> {{formattedTotal(homeData.withdrawalLastMonth)}} </span></div>
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="hover" class="echarts">
              <el-date-picker
                class="echarts-date"
                v-model="taskTimeRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                @change="getTaskEcharts"
                range-separator="-"
                :clearable="false"
                :picker-options="pickerOptions"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
              ></el-date-picker>
              <div ref="taskEchartsRef" style="width: 100%; height: 15.9rem;"></div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="hover" class="echarts">
              <el-date-picker
                class="echarts-date"
                v-model="payslipTimeRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                @change="getPayslipEcharts"
                range-separator="-"
                :clearable="false"
                :picker-options="pickerOptions"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
              ></el-date-picker>
              <div ref="payslipEcharts" style="width: 100%; height: 15.9rem;"></div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="hover" class="echarts">
              <el-date-picker
                class="echarts-date"
                v-model="separateTimeRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                @change="getSeparateEcharts"
                range-separator="-"
                :clearable="false"
                :picker-options="pickerOptions"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
              ></el-date-picker>
              <div ref="separateEchartsRef" style="width: 100%; height: 15.9rem;"></div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="hover" class="echarts">
              <el-date-picker
                class="echarts-date"
                v-model="withdrawalTimeRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                @change="getWithdrawalEcharts"
                range-separator="-"
                :clearable="false"
                :picker-options="pickerOptions"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
              ></el-date-picker>
              <div ref="withdrawalEchartsRef" style="width: 100%; height: 15.9rem;"></div>
            </el-card>
          </el-col>
        </el-row>

      </el-main>
      <el-aside :width="aside" v-if="showAside">
        <el-card shadow="hover">
          <div class="user">
            <el-avatar class="avatar" :size="60" :src="user.avatar" />
            <div class="info">
              <div class="money">
                <router-link to="/finance/finance">
                  {{formattedTotal(balance)}}
                </router-link>
              </div>
              <div>{{ user.phone }}</div>
              <div>{{ user.companyName }}</div>
            </div>
          </div>
        </el-card>
        <el-card class="notice"  shadow="hover">
          <div class="font-bold" style="display: block;">
            <span>公告</span>
          </div>
          <div class="grid">
            <el-empty :image-size="60" description="暂无数据" />
          </div>
        </el-card>
      </el-aside>

    </el-container>

  </div>
</template>

<script>
import store from "@/store";
import * as echarts from 'echarts';
import {
  getHomeData,
  getPayslipEchartsData,
  getSeparateEchartsData,
  getTaskEchartsData,
  getWithdrawalEchartsData
} from "@/api/system";
import {sumAccountBalance} from "@/api/transfer/transferAccountMerchantBalance";
import {getBalance} from "@/api/transfer/productBalance";

export default {
  name: "Index",
  data() {
    return {
      balance:0,
      loading:false,
      taskTimeRange:[],
      payslipTimeRange:[],
      separateTimeRange:[],
      withdrawalTimeRange:[],
      homeData:{
        taskToDay:0,
        taskYesterday:0,
        payslipToDay:0,
        payslipYesterday:0,
        separateToDay:0,
        separateYesterday:0,
        withdrawalToDay:0,
        withdrawalYesterday:0,

        taskCurrentMonth:0,
        taskLastMonth:0,
        payslipCurrentMonth:0,
        payslipLastMonth:0,
        separateCurrentMonth:0,
        separateLastMonth:0,
        withdrawalCurrentMonth:0,
        withdrawalLastMonth:0,

      },
      aside:"205px",
      taskEcharts: null,
      payslipEcharts:null,
      separateEcharts:null,
      withdrawalEcharts:null,
      resizeTimeout: null,
      user: store.getters.user,
      windowWidth: window.innerWidth,
      organizationType: store.getters.organizationType,
      pickerOptions: {
        // 设置最大可选日期为今天
        disabledDate: (time) => {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  computed: {
    showAside() {
      return this.windowWidth > 1092;
    },
  },
  created() {
    this.getData()
  },
  mounted() {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    this.taskTimeRange = [this.formatDate(start), this.formatDate(end)]
    this.payslipTimeRange = [this.formatDate(start), this.formatDate(end)]
    this.separateTimeRange = [this.formatDate(start), this.formatDate(end)]
    this.withdrawalTimeRange = [this.formatDate(start), this.formatDate(end)]

    this.$nextTick(() => {
      window.addEventListener('resize', this.handleResize);
    });

    const cachedData = JSON.parse(localStorage.getItem('domainData') || '{}');
    if (cachedData){
      this.user.avatar = `${process.env.VUE_APP_BASE_API}${cachedData.logo}`
    }
  },
  beforeDestroy() {
    // 移除监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    getData(){
      this.loading = true;

      if (this.organizationType === 4){
        sumAccountBalance({organizationId:store.getters.organizationId}).then(res=>{
          this.balance = res.data?res.data:0
        })
      }else {
        getBalance({}).then(res=>{
          this.balance = res.data?res.data:0
        })
      }

      getHomeData().then(res => {
        this.loading = false;
        this.homeData = res.data;
        this.initChart()
      }).catch(() => {
        this.loading = false;
      })
    },
    initChart(){
      // 销毁可能存在的旧实例
      if (this.taskEcharts) {
        this.taskEcharts.dispose();
      }
      if (this.payslipEchar) {
        this.payslipEchar.dispose();
      }
      if (this.separateEcharts) {
        this.separateEcharts.dispose();
      }
      if (this.withdrawalEcharts) {
        this.withdrawalEcharts.dispose();
      }

      this.getTaskEcharts()

      this.getPayslipEcharts()

      this.getSeparateEcharts()

      this.getWithdrawalEcharts()
    },

    getTaskEcharts(){
      getTaskEchartsData({startTime:this.taskTimeRange[0],endTime:this.taskTimeRange[1]}).then(res => {
        let data = res.data
        this.taskEcharts = echarts.init(this.$refs['taskEchartsRef']);
        this.taskEcharts.setOption(this.nearSevenCommonEChar("发放任务",data.dates,data.taskCounts,"个"));
      })
    },


    getPayslipEcharts(){
      getPayslipEchartsData({startTime:this.payslipTimeRange[0],endTime:this.payslipTimeRange[1]}).then(res => {
        let data = res.data
        this.payslipEchar = echarts.init(this.$refs['payslipEcharts']);
        this.payslipEchar.setOption(this.nearSevenCommonEChar("发放订单",data.dates,data.payslipData,"元"));
      })
    },

    getSeparateEcharts(){
      getSeparateEchartsData({startTime:this.separateTimeRange[0],endTime:this.separateTimeRange[1]}).then(res => {
        let data = res.data
        this.separateEcharts = echarts.init(this.$refs['separateEchartsRef']);
        this.separateEcharts.setOption(this.nearSevenCommonEChar("分润",data.dates,data.separateData,"元"));
      })
    },

    getWithdrawalEcharts(){
      getWithdrawalEchartsData({startTime:this.withdrawalTimeRange[0],endTime:this.withdrawalTimeRange[1]}).then(res => {
        let data = res.data
        this.withdrawalEcharts = echarts.init(this.$refs['withdrawalEchartsRef']);
        this.withdrawalEcharts.setOption(this.nearSevenCommonEChar("提现",data.dates,data.withdrawalData,"元"));
      })
    },

    nearSevenCommonEChar (title,name,data,unit) {
      return {
        backgroundColor: 'transparent',
        title: {
          text: title,
          left:"0%",
          textStyle: {
            fontWeight: 600,
            fontSize: 15,
            color: '#606266'
          },
        },
        grid: {
          left: '3%',
          right: '5%',
          bottom: '3%',
          top:"15%",
          containLabel: true
        },
        tooltip: {
          trigger: 'axis', // 触发方式，'axis' 表示坐标轴触发
          axisPointer: {
            type: 'line', // 指示器类型，'line' 表示线指示器
            lineStyle: {
              color: '#aaa' // 指示器的颜色
            }
          },
          formatter: function (params) {
            // 格式化提示框内容
            let result = '';
            params.forEach((item) => {
              result += `${item.data}${unit}<br/>`; // 生成显示的内容
            });
            return result;
          }
        },
        xAxis: [{
          type: 'category',
          boundaryGap: false,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "#333"
            },
          },
          axisLabel: {
            show: true,
            showMaxLabel: true,
          },
          data: name
        }],
        yAxis: [{
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "#333"
            },
          },
        }],
        series: [{
          name: '',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 5,
          showSymbol: false,
          lineStyle: {
            normal: {
              width: 3,
            }
          },

          areaStyle: { //区域填充样式
            normal: {
              //线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0,  color: 'rgba(61,234,255, 0.1)'},
                { offset: 0.7,  color: 'rgba(61,234,255, 0)'}
              ], false),

              shadowColor: 'rgba(17,169,131,0.09)', //阴影颜色
              shadowBlur: 0.1 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
            }
          },
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
                offset: 0,
                color: 'rgba(17,169,131,0.1)' // 浅蓝色
              }, {
                offset: 1,
                color: 'rgba(17,169,131,1)' // 深蓝色
              }])
            },
          },
          data: data
        }],
        dataZoom: [
          {
            type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
            // startValue: data.length - 18,
            // endValue: data.length,
            start: (name.length - 19) / name.length * 100,
            // end: 100
          }]
      }
    },

    resizeChart() {
      if (this.taskEcharts) {
        this.taskEcharts.resize();
      }
      if (this.payslipEchar) {
        this.payslipEchar.resize();
      }
      if (this.separateEcharts) {
        this.separateEcharts.resize();
      }
      if (this.withdrawalEcharts) {
        this.withdrawalEcharts.resize();
      }
    },

    handleResize() {
      clearTimeout(this.resizeTimeout);
      this.resizeTimeout = setTimeout(() => this.resizeChart(), 100);
      this.windowWidth = window.innerWidth;
    },
    formattedTotal(amount) {
      if (!amount){
        return "￥0";
      }
      const formatter = new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })

      return formatter.format(amount)
    },
    // 定义日期格式化函数
    formatDate (date) {
      const year = date.getFullYear();
      // 月份和日期不足两位数时补零
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<style scoped lang="scss">
.app-container{
  .el-container{
    gap: 10px;
    height: 100%;
  }
  .el-card {
    margin-bottom: 10px;
    ::v-deep .el-card__body {
      padding: 15px;
    }
  }
  .el-main {
    padding: 2.5px;
  }
  .el-aside{
    overflow: hidden;
    .user{
      gap: 10px;
      display: flex;
      align-items: center;
      flex-direction: column;
      .info{
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        div {
          /* 限制宽度，根据实际需求调整 */
          width: 85%;
          padding: 12px 0;
          /* 强制文本在一行显示 */
          white-space: nowrap;
          /* 超出部分隐藏 */
          overflow: hidden;
          text-align: center;
          /* 超出部分显示省略号 */
          text-overflow: ellipsis;
        }
      }
      .money {
        cursor: pointer;
        font-size: 18px;
        font-weight: 700;
        color: #11A983FF
      }
    }
    .notice{
      height: 36rem;;
    }
  }


  .card{
    gap: 10px;
    height: 80px;
    display: flex;
    font-size: 14px;
    align-items: center;
    justify-content: space-between;

    .money {
      cursor: pointer;
      font-size: 18px;
      font-weight: 700;
      color: #11A983FF
    }
    .font-bold {
      gap: 10px;
      display: flex;
      font-weight: 600;
      color: #606266;
      font-size: 14px;
      flex-direction: column;
      justify-content: flex-start;
      .text {
        font-size: 16px;
      }
      .number {
        font-size: 12px;
        .money {
          cursor: pointer;
          font-size: 12px;
          color: #11A983FF
        }
      }

    }
  }
  .echarts{
    position: relative;
    .el-card {
      ::v-deep .el-card__body {
        padding: 15px 0 15px 15px;
      }
    }
    .echarts-date{
      right: 15px;
      z-index: 100;
      position: absolute;
    }
  }


  //.user {
  //  display: flex;
  //  flex-direction: row;
  //  align-items: center;
  //  font-size: 14px;
  //
  //  .avatar {
  //    width: 80px;
  //    height: 80px;
  //    border-radius: 50%;
  //  }
  //
  //  .info {
  //    flex-grow: 1;
  //    margin-left: 20px;
  //    height: 80px;
  //    display: flex;
  //    flex-direction: column;
  //    align-items: flex-start;
  //    justify-content: space-around;
  //  }
  //
  //  .withdraw {
  //
  //    .prompt {
  //      font-weight: 300px;
  //      color: black;
  //    }
  //
  //    .money {
  //      font-size: 18px;
  //      font-weight: 700;
  //      color: #f56c6c
  //    }
  //  }
  //}
}
</style>

